<template>
  <div class="table-renderer">
    <el-table
      :data="tableData"
      :border="border"
      :stripe="stripe"
      style="width: 100%">
      <template v-for="column in columns" :key="column.prop">
        <el-table-column
          :prop="column.prop"
          :label="column.label"
          :width="column.width">
          <template #default="scope">
            <template v-if="column.type === 'image'">
              <el-image
                :src="scope.row[column.prop]"
                :preview-src-list="[scope.row[column.prop]]"
                fit="cover"
                style="width: 50px; height: 50px" />
            </template>
            <template v-else-if="column.type === 'date'">
              {{ formatDate(scope.row[column.prop]) }}
            </template>
            <template v-else>
              {{ scope.row[column.prop] }}
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <div class="table-pagination" v-if="showPagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const props = defineProps({
  columns: {
    type: Array,
    default: () => []
  },
  border: {
    type: Boolean,
    default: true
  },
  stripe: {
    type: Boolean,
    default: true
  },
  apiUrl: {
    type: String,
    default: ''
  },
  pageSize: {
    type: Number,
    default: 10
  },
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100]
  },
  showPagination: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update:data'])

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(props.pageSize)
const total = ref(0)

// 简单的日期格式化函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString()
}

// 获取表格数据
const getTableData = async () => {
  if (!props.apiUrl) return

  try {
    const response = await fetch(`${props.apiUrl}?page=${currentPage.value}&size=${pageSize.value}`)
    const data = await response.json()
    tableData.value = data.list
    total.value = data.total
    emit('update:data', data)
  } catch (error) {
    console.error('获取表格数据失败:', error)
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.table-renderer {
  width: 100%;
}

.table-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style> 